package com.koo.modules.product.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.koo.common.response.R;
import com.koo.common.utils.PageUtils;
import com.koo.common.utils.UserUtils;
import com.koo.common.utils.excel.BaseDateConverter;
import com.koo.common.utils.excel.EasyExcelUtil;
import com.koo.modules.product.entity.ProductInfoEntity;
import com.koo.modules.product.entity.vo.ProductVo;
import com.koo.modules.product.service.ProductInfoService;
import com.koo.modules.comm.service.SynDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * @author charlin
 * @email 136137465@qq.com
 * @date 2022-12-20 16:45:05
 */
@Slf4j
@Api(tags = "主要商品资料")
@RestController
@RequestMapping("product/info")
public class ProductInfoController {

    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private SynDataService synDataService;

    /**
     * 获取最大商品code
     */
    @ApiOperation("获取最大商品code")
    @RequestMapping("/getMaxCode")
    @RequiresPermissions("base:baseproduct:list")
    public R getMaxCode() {
        String code = productInfoService.getMaxCode();
        return R.ok().put(code);
    }

    @ApiOperation("获取列表")
    @RequestMapping("/list")
    @RequiresPermissions("base:baseproduct:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = productInfoService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{productId}")
    @RequiresPermissions("goods:goods:info")
    public R info(@ApiParam(value = "主键", required = true) @PathVariable("productId") Long productId) {
        ProductVo baseProduct = productInfoService.findById(productId);
        return R.ok().setData(baseProduct);
    }

    @ApiOperation("保存")
    @RequestMapping("/save")
    @RequiresPermissions("base:baseproduct:save")
    public R save(@RequestBody ProductVo productVo) {
        productInfoService.saveProduct(productVo);
        return R.ok();
    }


    @ApiOperation("修改")
    @RequestMapping("/updateById")
    @RequiresPermissions("base:baseproduct:update")
    public R updateById(@RequestBody ProductInfoEntity baseProduct) {
        productInfoService.updateById(baseProduct);
        return R.ok();
    }

    @ApiOperation("修改状态")
    @PutMapping("/updateStatus/{productId}/{status}")
    @RequiresPermissions("base:baseproduct:update")
    public R updateStatus(@PathVariable("productId") String productId, @PathVariable("status") Integer status) {
        ProductInfoEntity baseProduct = new ProductInfoEntity();
        baseProduct.setProductId(Long.parseLong(productId));
        baseProduct.setStatus(status);
        productInfoService.updateById(baseProduct);
        return R.ok();
    }

    @ApiOperation("修改全部属性")
    @RequestMapping("/update")
    @RequiresPermissions("base:baseproduct:update")
    public R update(@RequestBody ProductVo productVo) {
        productInfoService.update(productVo);
        return R.ok();
    }

    @ApiOperation("删除")
    @RequestMapping("/delete")
    @RequiresPermissions("base:baseproduct:delete")
    public R delete(@RequestBody String[] productIds) {
        productInfoService.removeByIds(Arrays.asList(productIds));
        return R.ok();
    }


    @ApiOperation("导入")
    @RequestMapping("/importData")
    @RequiresPermissions("base:baseproduct:import")
    @Transactional(rollbackFor = {Exception.class})
    public R importData(@RequestParam("file") MultipartFile file) {
        EasyExcelUtil<ProductInfoEntity> excelUtil = new EasyExcelUtil(productInfoService);
        try {
            // 读取文件流
            EasyExcel.read(
                            file.getInputStream(),
                            ProductInfoEntity.class,
                            excelUtil)// 监听器
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .registerConverter(new BaseDateConverter.LocalDateConverter())
                    .doRead();
        } catch (IOException e) {
            return R.error("导入失败!");
        }
        return R.ok("导入成功!");
    }

    @ApiOperation("导出")
    @GetMapping("/exportData")
    @RequiresPermissions("base:baseproduct:export")
    public void exportData(HttpServletResponse response, @RequestParam("type") Integer type) {
        try {
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = EasyExcelUtil.initExportParams("商品资料报表", response);
            if (type == 1) {
                List<ProductInfoEntity> list = productInfoService.list();
                EasyExcel.write(response.getOutputStream()
                                , ProductInfoEntity.class)
                        .registerWriteHandler(horizontalCellStyleStrategy)
                        .sheet()
                        .doWrite(list);
            } else {
                List<ProductVo> list = productInfoService.listProduct();
                EasyExcel.write(response.getOutputStream()
                                , ProductVo.class)
                        .registerWriteHandler(horizontalCellStyleStrategy) //加载样式
                        .sheet()
                        .doWrite(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ApiOperation("获取需要下载的药品")
    @GetMapping("/getDownloadCount")
    @RequiresPermissions("base:baseproduct:download")
    public R getDownloadCount(){
        Integer count = synDataService.getDownloadCount("product_info", UserUtils.getStoreId());
        return R.ok().setData(count);
    }

    @ApiOperation("下载药品")
    @GetMapping("/downloadProductFromCenter")
    @RequiresPermissions("base:baseproduct:download")
    public R downloadProductFromCenter(){
        return synDataService.downloadProductFromCenter("product_info", UserUtils.getStoreId());
    }


    @ApiOperation("获得价格信息")
    @GetMapping("/getPriceCount/{priceType}")
    @RequiresPermissions({"base:baseproduct:upprice", "base:baseproduct:downprice"})
    public R getPriceCount(@PathVariable Integer priceType){
        Integer count = productInfoService.getPriceCount(priceType, UserUtils.getStoreId());
        return R.ok().setData(count);
    }

//    @Autowired
//    private UserService userService;
//
//    /**
//     * 导出本地用户userId与聚力对应userId
//     *
//     * @return 是否导出成功
//     * @throws Exception
//     */
//    @GetMapping("/exportUser")
//    @ResponseBody
//    public void exportJuLiData(HttpServletResponse response) throws Exception {
//        String operName = "charlin"; // 操作人
//        userService.exportUser(response, operName);
//    }
//
//    /**
//     * 导入本地用户userId与聚力对应userId
//     *
//     * @param file 导入文件
//     * @return 是否导入成功
//     * @throws Exception
//     */
//    @PostMapping("/importUser")
//    @ResponseBody
//    public Boolean importUser(@RequestParam MultipartFile file) throws Exception {
//        String operName = "charlin"; // 操作人
//        return userService.importUser(file, false, operName);
//    }


}
